<template>
  <div>
    <el-upload
      :class="{ 'active': !showList && fileList.length > 0 }"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="OnRemove"
      :on-change="Onchange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览" :visible="isShowGialog" :modal="false" @close="isShowGialog=false">
      <el-row type="flex" justify="center">
        <img :src="dialogImageUrl" alt="" style="width:100%">
      </el-row>
    </el-dialog>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDJQHq9AuNZU8WcS0HH0SdWBYeT1II1TfZ',
  SecretKey: 'e18yXooY1C6j5AyWmlTu4wXrviETR8Yh'
})
export default {
  props: {
    showList: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      percentage: 0, // 进度条进度
      isShowProgress: false,
      isShowGialog: false,
      dialogImageUrl: '',
      fileList: []
    }
  },
  methods: {
    onPreview(file) {
      this.dialogImageUrl = file.url
      this.isShowGialog = true
    },
    OnRemove(file, fileList) {
      this.fileList = fileList
    },
    Onchange(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      // console.log(1, file)
      // 校验上传大小
      const allowSize = 2 * 1024 * 1024
      if (file.size > allowSize) {
        this.$message.warning('上传大小不能超过 2M ')
        return false
      }
      // 校验类型
      const writeList = ['image/jpeg', 'image/png']
      if (!writeList.includes(file.type)) {
        this.$message.warning('上传图片只支持 jpg 或 png 格式')
        return false
      }
    },
    // 上传腾讯云
    upload(file) {
      // 显示进度条
      console.log(file)
      this.isShowProgress = true
      // console.log(file)
      cos.putObject({
        Bucket: '69hr-1308572205', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: file.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          // console.log(22, progressData)
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // 上传腾讯云后的回调
        this.fileList[this.fileList.length - 1].url = 'http://' + data.Location
        this.fileList[this.fileList.length - 1].status = 'success'
        setTimeout(() => {
          // 关闭进度条
          this.isShowProgress = false
        }, 1000)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .active {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
<style lang="scss" >
img{
  object-fit: cover;
}
</style>
